%%%-------------------------------------------------------------------
%%% @author chenlong
%%% @copyright (C) 2019, <COMPANY>
%%% @doc
%%% 离线事件处理
%%% @end
%%% Created : 26. 三月 2019 14:23
%%%-------------------------------------------------------------------
-module(role_offline).
-author("chenlong").

-include("common.hrl").

%% API
-export([onOfflineEvent/0,addOfflineEvent/2]).

%%=================================EXPORTED FUNCTION==============================================
%%玩家进程
onOfflineEvent() ->
	RoleID = role_data:getRoleID(),
	List = db_sql:getRoleOfflineEvent(RoleID),
	lists:foreach(fun({EventID, EventMsg}) ->
		case doOfflineEvent(EventMsg) of
			?FALSE -> ok;
			_ -> db_sql:deleteEvent(EventID)
		end
		end,List),
	ok.

%%公共进程
%%添加离线事件
addOfflineEvent(RoleID, Event) ->
	db_sql:addRoleOfflineEvent(RoleID,Event),
	%%尝试通知玩家进程，去获取离线事件
	catch (role_lib:sendToPlayerServer(RoleID, {offlineEvent})).

%%=================================LOCAL FUNCTION==============================================
%%玩家进程
doOfflineEvent({?OFFLINE_EVENT_TYPE_BATTLE_END, IsWin0}) ->
	IsWin = util:int2bool(IsWin0),
	Role = role_data:getRole(),
	{WinScore, LoseScore}=battle_lib:getCfgBattle(battle_score),
	Role1 = case IsWin of
		?TRUE ->
			Role#role{score = Role#role.score + WinScore};
		_ ->
			Role#role{score = max(0,Role#role.score - LoseScore)}
	end,
	role_data:setRole(Role1),
	ok;
doOfflineEvent(EventMsg) ->
	?ERR("doOfflineEvent EventMsg=~p",[EventMsg]),
	?FALSE.